package com.example.socket;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;

/**
 * @author yzh
 * @version 1.0
 * @date 2021/7/28 14:51
 */
@Slf4j
public class MyServer {
    private static final int SIZE = 1024;
    private Selector selector;
    private ByteBuffer byteBuffer;
    private ServerSocketChannel serverSocketChannel;
    private int remoteClientNum = 0;
    public MyServer(int port) {
        try {
            initChannel(port);
        } catch (IOException e) {
            System.exit(-1);
        }

    }
    private void initChannel(int port) throws IOException {
        // 打开 channel
        serverSocketChannel = ServerSocketChannel.open();
        // 设置为非阻塞模式
        serverSocketChannel.configureBlocking(false);
        // 绑定端口
        serverSocketChannel.bind(new InetSocketAddress(port));
        log.info("listener on port: {}", port);
        // 创建选择器
        selector = Selector.open();
        // 向选择器注册通道
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        // 分配缓冲区大小
        byteBuffer = ByteBuffer.allocate(SIZE);
    }
}
